//
//  UserAccount.swift
//  DSWeibo
//
//  Created by liuzhu on 2018/11/13.
//  Copyright © 2018 liuzhu. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding {

    
    var access_token:String?
    var expires_in:NSNumber?
    var uid:String?
    var expires_Date:NSDate?    //保存用户过期时间
    var avatar_large:String?
    var screen_name:String?
    init(dict:[String:AnyObject]){
        super.init()
        //初始化的时候赋值，不会调用didSet方法
        access_token = dict["access_token"] as? String
        expires_in = dict["expires_in"] as? NSNumber
        uid = dict["uid"] as? String
        expires_Date = NSDate(timeIntervalSinceNow: (expires_in?.doubleValue)!)
        //setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        print(key)
    }
    
//    override var description: String{
//        let properties = ["access_token","expires_in","uid"]
//        let dict = self.dictionaryWithValues(forKeys: properties)
//        return "\(dict)"
//    }
    
    func loadUserInfo(finished:@escaping (_ account:UserAccount?,_ error:NSError?)->()){
        //assert(access_token == nil,"没有授权")
        let path = "2/users/show.json"
        let params = ["access_token":access_token,"uid":uid]
        NetWorkTools.shareNetworkTools().get(path, parameters: params, progress: { (_) in
            
        }, success: { (_, JSON) in
            
            //判断字典是否有值
            if let dict = JSON as? [String:AnyObject]{
                self.screen_name = dict["screen_name"] as? String
                self.avatar_large = dict["avatar_large"] as? String
                //self.saveAccount()
                finished(self,nil)
                return
            }
            finished(nil,nil)
        }) { (_, error) in
            finished(nil,nil)
        }
    }
    
    class func userLogin()->Bool {
        return UserAccount.loadAccount() != nil
    }
    
    func saveAccount(){
        NSKeyedArchiver.archiveRootObject(self, toFile: "account.plist".cacheDir())
    }
    
    static var account:UserAccount?
    class func loadAccount()->UserAccount?{
        if account != nil
        {
            return account
        }
        account = NSKeyedUnarchiver.unarchiveObject(withFile:  "account.plist".cacheDir()) as? UserAccount
        //判断授权信息是否过期
        if account?.expires_Date?.compare(NSDate() as Date) == ComparisonResult.orderedAscending{
            return nil
        }
        return account
    }
    
    //将对象写入
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expires_in, forKey: "expires_in")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(expires_Date, forKey: "expires_Date")
        aCoder.encode(screen_name, forKey: "screen_name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
    }
    
    //读取对象
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey: "access_token")as?String
        expires_in = aDecoder.decodeObject(forKey: "expires_in")as?NSNumber
        uid = aDecoder.decodeObject(forKey: "uid")as?String
        expires_Date = aDecoder.decodeObject(forKey: "expires_Date") as?NSDate
        screen_name = aDecoder.decodeObject(forKey: "screen_name") as?String
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
    }
    
    //required init
}
